﻿namespace Raven
{
    public class GoalExplore : GoalComposite<RavenBot>
    {
        private Vector2 _currentDestination;

        //set to true when the destination for the exploration has been established
        private bool _destinationIsSet;

        public GoalExplore(RavenBot owner) : base(owner, GoalType.goal_explore)
        {
            _destinationIsSet = false;
        }

        public override void Activate()
        {
            _status = GoalStatus.active;

            //if this goal is reactivated then there may be some existing subgoals that
            //must be removed
            RemoveAllSubgoals();

            if (!_destinationIsSet)
            {
                //grab a random location
                _currentDestination = _owner.GetWorld().GetMap().GetRandomNodeLocation();

                _destinationIsSet = true;
            }

            //and request a path to that position
            _owner.GetPathPlanner().RequestPathToPosition(_currentDestination);

            //the bot may have to wait a few update cycles before a path is calculated
            //so for appearances sake it simple ARRIVES at the destination until a path
            //has been found
            AddSubgoal(new GoalSeekToPosition(_owner, _currentDestination));
        }

        public override GoalStatus Process()
        {
            //if status is inactive, call Activate()
            ActivateIfInactive();

            //process the subgoals
            _status = ProcessSubgoals();

            return _status;
        }

        public override void Terminate()
        {
            
        }

        public override bool HandleMessage(Telegram msg)
        {
            //first, pass the message down the goal hierarchy
            bool bHandled = ForwardMessageToFrontMostSubgoal(msg);

            //if the msg was not handled, test to see if this goal can handle it
            if (bHandled == false)
            {
                switch(msg.msg)
                {
                    case MessageType.Msg_PathReady:

                        //clear any existing goals
                        RemoveAllSubgoals();

                        AddSubgoal(new GoalFollowPath(_owner,
                            _owner.GetPathPlanner().GetPath()));

                        return true; //msg handled


                    case MessageType.Msg_NoPathAvailable:

                        _status = GoalStatus.failed;

                        return true; //msg handled

                    default: return false;
                }
            }

            //handled by subgoals
            return true;
        }
    }
}